package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.center.pojo.MachineStatus;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.constant.SysConstant;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.AdAccountFee;
import com.tbit.uqbike.client.pojo.Machine;
import com.tbit.uqbike.client.pojo.Point;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备最后状态
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@Controller
@RequestMapping("/machineStatus")
public class MachineStatusController {
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    private CalibrateService calibrateService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private MachineFeeService machineFeeService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private AdAccountFeeService adAccountFeeService;

    /**
     * 根据设备编号获取状态
     *
     * @param token    令牌
     * @param userCode 车辆编号
     * @param mapType  地图类型
     * @param session  会话
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/getByMachineNO")
    public void getByMachineNO(String token, String userCode, Integer mapType, HttpSession session,
                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            /* 校验 */
            /**暂时先用设备编号字段代替用户码，后期统一修改*/
            Assert.hasLength(userCode, "-30006", "machineNO不能为空");

            if (mapType == null) {
                mapType = SysConstant.GOOGLE;
            }
            Machine machine = machineService.getByUserCode(userCode);
            if (machine == null) {
                throw new BaseException("-30005", "车辆不存在");
            }
            MachineStatus machineStatus = machineStatusService.getByMachineNO(machine.getMachineNO(), mapType);

            User user = tokenService.getUser(token);

            Integer freeTimes = -1;
            AdAccountFee adAccountFee = adAccountFeeService.getByAccountId(machine.getAccountId(), machine.getMachineId());
            if (adAccountFee != null) {
                Integer accountFreeTime = adAccountFee.getFreeRideTime();
                if (accountFreeTime == null) {
                    accountFreeTime = 0;
                }
                if (accountFreeTime == 0) {
                    freeTimes = -1;
                } else {
                    Integer count = rideLogService.getTodayNo(user.getUserId(), DateTimeUtil.getNowTimeYMD());
                    if (count >= accountFreeTime) {
                        freeTimes = 0;
                    } else {
                        freeTimes = accountFreeTime - count;
                    }
                }

            }

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, machineStatus);
            map.put("times", freeTimes);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    /**
     * 根据设备编号获取状态
     *
     * @param userCode 用户代码
     * @param mapType  地图类型
     * @param session  会话
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/getByUserCode")
    public void getByUserCode(String userCode, Integer mapType, HttpSession session,
                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            /* 校验 */

            Assert.hasLength(userCode, "-30006", "machineNO不能为空");

            if (mapType == null) {
                mapType = SysConstant.BAIDU;
            }
            Machine machine = machineService.getByUserCode(userCode);
            if (machine == null) {
                throw new BaseException("-30005", "车辆不存在");
            }
            MachineStatus machineStatus = machineStatusService.getByMachineNO(machine.getMachineNO(), mapType);

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, machineStatus);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    /**
     * 获取附近车辆
     *
     * @param accountId   品牌id
     * @param adAccountId 区域id
     * @param lo          经度
     * @param la          纬度
     * @param radius      半径
     * @param mapType     地图类型
     * @param response    响应
     * @ignoreParams request
     */
    @RequestMapping("/getNearMachine")
    public void getNearMachine(Integer accountId, Integer adAccountId, Double lo, Double la, Integer radius, Integer mapType,
                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();

        try {
            Assert.notNull(accountId, "-10001", "平台id不能为空");
            Assert.notNull(lo, "-2001", "经度不能为空");
            Assert.notNull(la, "-2002", "纬度不能为空");
            // 新需求兼容旧版本，radius 前端给值就根据参数来，不给值就读配置
            // Assert.notNull(radius, "-2003", "半径不能为空");

            if (mapType == null) {
                mapType = SysConstant.GOOGLE;
            }

            /*校准百度经纬度为原始经纬度*/
            Point point = new Point(lo, la);
            point = calibrateService.calibrate(point, mapType, SysConstant.ORIGINAL);

            List<MachineStatus> machineStatuses = machineStatusService.getNearMachineNew(accountId, adAccountId, radius, mapType, point.getX(), point.getY());

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, machineStatuses);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /**
     * 获取可用优惠套餐信息
     *
     * @param userCode 车辆编号
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/getDiscountByMachineNO")
    public void getDiscountByMachineNO(String token, String userCode, HttpServletRequest request,
                                       HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            Assert.hasLength(userCode, "-30006", "车辆编号不能为空");
            User user = tokenService.getUser(token);
            machineFeeService.getDiscountByMachineNO(user, userCode, map);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }
}